import React, { Component } from "react";
import "./public/index.css";

export default class PreviewBox extends Component {
  constructor(props) {
    super(props);
    const { width, height, data } = this.props;
    this.state = {
      preview: false,
      process: 0
    };
  }

  strategies = {
    mousemove: function (event) {
      const {
        width,
        data: {
          previewPic: { len_x, len_y }
        }
      } = this.props;
      var process = Math.floor((event.clientX / width) * (len_x * len_y));
      this.setState({ process });
    },
    mouseenter: function () {
      this.setState({ preview: true });
    },
    mouseleave: function () {
      this.setState({ preview: false });
    }
  };

  mouseEventHandle = event => {
    var fn = this.strategies[event.type];
    if (typeof fn !== "function") return;
    this.strategies[event.type].call(this, event);
  };

  render() {
    const { preview, process } = this.state;
    const {
      width,
      height,
      data: {
        title,
        duration,
        link,
        pic,
        previewPic: { src, len_x, len_y },
        stat: { view, like }
      }
    } = this.props;
    return (
      <div className="v-pre-box">
        <div className="v-pre-pic">
          {/* 预览图主体 */}
          <a
            href={link}
            target="_blank"
            onMouseEnter={event => {
              this.mouseEventHandle(event);
            }}
            onMouseLeave={event => {
              this.mouseEventHandle(event);
            }}
            onMouseMove={event => {
              this.mouseEventHandle(event);
            }}
          >
            {/* 首页图 */}
            <img src={pic} alt="" />
            {/* 点赞浏览量时长等信息栏 */}
            <div className="v-pre-count">
              <div className="v-pre-count-left">
                <span>{(view / 10000).toFixed(1)}万</span>
                <span>{(like / 10000).toFixed(1)}万</span>
              </div>
              <div className="v-pre-count-right">
                <span>{`${Math.floor(duration / 60)}:${duration % 60}`}</span>
              </div>
            </div>
            {/* 多帧预览图frame */}
            <div
              className="v-pre-previewframe"
              style={{
                backgroundPosition: `${(-process % len_x) * width}px ${
                  Math.floor(process / len_y) * height
                }px`,
                backgroundImage: `url(${src})`,
                opacity: preview * 1,
                backgroundSize: `${width * len_x}px ${height * len_y}px`
              }}
            >
              <div className="v-pre-fpbar">
                <span
                  style={{ width: (process * 100.0) / (len_x * len_y) + "%" }}
                ></span>
              </div>
            </div>
          </a>
        </div>
        {/* 下方标题 */}
        <a href={link} target="_blank" title={title} className="v-pre-title">
          {title}
        </a>
      </div>
    );
  }
}
